const Archiver = require("archiver");
const path = require("path");
const fs = require("fs");
const lib_username = require("./username");
const Toolbox = require("./Toolbox");


/**
 * @returns {Promise<{ok:Boolean,msg,data:{tar_path:String}}>}
 * @param {String} source_dir 
 * @param {String} target_path full_path as tar file's path;假设这个path是不会出现和已经有的文件冲突的
 */
function tarDir(source_dir, target_path) {
  return new Promise(async resolve => {
    let arc = Archiver("tar");
    let target_dirname = path.dirname(target_path);
    let o_check_stats = await Toolbox.getStats(target_dirname);
    if (!o_check_stats.ok) {
      let o_mkdirp = await Toolbox.mkdirp(target_dirname);
      if (!o_mkdirp.ok) {
        return resolve({
          ok: false,
          msg: `error when mkdirp:${o_mkdirp.msg}`
        })
      }
    }
    let output = fs.createWriteStream(target_path);
    arc.append(`${lib_username.USERNAME}`, { name: `I-AM.txt` });
    arc.directory(source_dir, path.basename(source_dir));
    arc.on("error", (err) => {
      resolve({
        ok: false,
        msg: `arc.on(error):${err.message}`
      })
    });
    arc.on("finish", () => {
      resolve({
        ok: true,
        msg: "ok",
        data: {
          tar_path: target_path
        }
      })
    })
    arc.pipe(output);
    arc.finalize();
  })
}

module.exports = {
  tarDir
}